package com.xmwzw.catpu.http;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mikepenz.materialize.drawable.PressedEffectStateListDrawable;
import com.xmwzw.catpu.BaseApplication;
import com.xmwzw.catpu.bean.SoftBean;
import com.xmwzw.catpu.http.bean.BaseRespond;
import com.xmwzw.catpu.http.bean.DetailBean;
import com.xmwzw.catpu.http.bean.LoginRespond;
import com.xmwzw.catpu.http.bean.TypeBean;
import com.xmwzw.catpu.http.listener.DetailListener;
import com.xmwzw.catpu.http.listener.ItemListener;
import com.xmwzw.catpu.http.listener.LoginListener;
import com.xmwzw.catpu.http.listener.LogoutListener;
import com.xmwzw.catpu.http.listener.RegisterListener;
import com.xmwzw.catpu.http.listener.SearchListener;
import com.xmwzw.catpu.http.listener.TypeListener;
import com.xmwzw.catpu.util.Constant;
import com.xmwzw.catpu.util.SPFaceUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BaseRequest {
    private static final String TAG = BaseRequest.class.getSimpleName();

    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    private static final MediaType XML = MediaType.parse("text/x-markdown; charset=utf-8");


    private static BaseRequest instance;

    public synchronized static BaseRequest getInstance() {

        if (instance == null) {
            instance = new BaseRequest();

        }

        return instance;

    }



    private interface BaseRespondInterface {
        void onRespond(Response response);
    }

    /**
     * post请求
     *
     * @param url
     * @param requestBean
     * @param respondInterface
     */
    private void HttpPostRequest(String url, Object requestBean, final BaseRespondInterface respondInterface) {
        OkHttpClient client = RetrofitUtil.getInstance().getClient();
        RequestBody body = RequestBody.create(JSON, new Gson().toJson(requestBean));

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                if (respondInterface != null) {
                    respondInterface.onRespond(response);
                }

            }
        });
    }

    private void HttpPostRequest(String url, RequestBody body, final BaseRespondInterface respondInterface) {

        OkHttpClient client = RetrofitUtil.getInstance().getClient();

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                if (respondInterface != null) {
                    respondInterface.onRespond(response);
                }

            }
        });
    }

    /**
     * get 请求
     *
     * @param url
     * @param respondInterface
     */
    private void HttpGetRequest(String url, final BaseRespondInterface respondInterface) {

        OkHttpClient client = RetrofitUtil.getInstance().getClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "getAccessToken: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (respondInterface != null) {
                    respondInterface.onRespond(response);
                }
            }
        });
    }


    public void getTypes(final TypeListener listener) {
        String url = "http://47.105.156.209:8080/Qt/Home/homeType";
        HttpGetRequest(url, new BaseRespondInterface() {
            @Override
            public void onRespond(Response response) {
                try {
                    String data = response.body().string();
                    List<TypeBean> list = new Gson().fromJson(data, new TypeToken<List<TypeBean>>() {
                    }.getType());

                    listener.getType(list);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public void getItems(int type, final ItemListener listener) {
        String url = "http://47.105.156.209:8080/Qt/Home/homeItems?type=" + type;
        HttpGetRequest(url, new BaseRespondInterface() {
            @Override
            public void onRespond(Response response) {
                try {
                    String data = response.body().string();
                    List<SoftBean> list = new Gson().fromJson(data, new TypeToken<List<SoftBean>>() {
                    }.getType());

                    listener.getItems(list);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public void getDetail(int id, final DetailListener listener) {
        String url = "http://47.105.156.209:8080/Qt/Home/home_detail?id=" + id;
        HttpGetRequest(url, new BaseRespondInterface() {
            @Override
            public void onRespond(Response response) {
                try {
                    String data = response.body().string();
                    DetailBean detailBean = new Gson().fromJson(data, DetailBean.class);

                    listener.getDetail(detailBean);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public static void postAsync(String url, Map<String, String> params, Callback callback) {
        OkHttpClient client = RetrofitUtil.getInstance().getClient();
        Request.Builder builder = new Request.Builder().url(url);

        FormBody.Builder formBody = new FormBody.Builder();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formBody.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody requestBody = formBody.build();
        Request request = builder.post(requestBody).build();
        client.newCall(request).enqueue(callback);
    }

    public void register(String username, String paw, String rePaw, final RegisterListener registerListener) {
        String url = "http://47.105.156.209:8080/Qt/Home/sign_up";
        RequestBody formBody = new FormBody.Builder()
                .add("username", username)
                .add("passwd", paw)
                .add("repasswd", rePaw)
                .build();
        HttpPostRequest(url, formBody, new BaseRespondInterface() {
            @Override
            public void onRespond(Response response) {
                try {
                    String data = response.body().string();
                    Log.d(TAG, "onRespond: " + data);
                    BaseRespond respond = new Gson().fromJson(data, BaseRespond.class);
                    registerListener.getRespond(respond);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public void login(String username, String paw, final LoginListener loginListener) {
        String url = "http://47.105.156.209:8080/Qt/Home/sign_in";

        RequestBody formBody = new FormBody.Builder()
                .add("username", username)
                .add("passwd", paw)
                .build();
        HttpPostRequest(url, formBody, new BaseRespondInterface() {
            @Override
            public void onRespond(Response response) {
                try {
                    String data = response.body().string();
                    Log.d(TAG, "onRespond: " + data);
                    LoginRespond respond = new Gson().fromJson(data, LoginRespond.class);
                    loginListener.getRespond(respond);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void logout(String username, String token, final LogoutListener logoutListener) {
        String url = "http://47.105.156.209:8080/Qt/Home/sign_out";

        RequestBody formBody = new FormBody.Builder()
                .add("username", username)
                .add("token", token)
                .build();

        HttpPostRequest(url, formBody, new BaseRespondInterface() {
            @Override
            public void onRespond(Response response) {
                try {
                    String data = response.body().string();
                    Log.d(TAG, "onRespond: " + data);
                    BaseRespond respond = new Gson().fromJson(data, BaseRespond.class);
                    logoutListener.getRespond(respond);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void search(String content, final SearchListener listener) {
        String url = "http://47.105.156.209:8080/Qt/Home/search?appname=" + content;

        HttpGetRequest(url, new BaseRespondInterface() {
            @Override
            public void onRespond(Response response) {
                try {
                    String data = response.body().string();
                    List<SoftBean> list = new Gson().fromJson(data, new TypeToken<List<SoftBean>>() {
                    }.getType());
                    listener.getSearch(list);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public void changePwd(String mAccount, String mOldPaw, String mNewPaw,
                          final RegisterListener listener ) {

        String url ="http://47.105.156.209:8080/Qt/Home/resetpwd";

        String token = SPFaceUtils.get(BaseApplication.getInstance(), Constant.KEY_LOGIN_TOKEN,"");

        RequestBody formBody = new FormBody.Builder()
                .add("username", mAccount)
                .add("token", token)
                .add("oldpwd",mOldPaw)
                .add("newpwd",mNewPaw)
                .build();
        HttpPostRequest(url, formBody,new BaseRespondInterface() {
            @Override
            public void onRespond(Response response) {
                try {
                    String data = response.body().string();
                    Log.d(TAG, "onRespond: " + data);
                    BaseRespond respond = new Gson().fromJson(data, BaseRespond.class);
                    listener.getRespond(respond);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
